package web.servlet.userlist.web.servelt;

import org.apache.commons.beanutils.BeanUtils;
import web.servlet.userlist.domin.User;
import web.servlet.userlist.service.UserService;
import web.servlet.userlist.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author: 18148
 * @Date: 2020-06-21 16:01:05
 */
@WebServlet("/insertServlet")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService service=new UserServiceImpl();
        int i = service.add(user);
        if(i>0){
            String path = req.getContextPath();
            resp.sendRedirect(path+"/listServlet");
        }else if(i==0){
            req.setAttribute("add_error","添加失败");
            req.getRequestDispatcher("/userlist/add.jsp").forward(req,resp);
        }else {
            req.setAttribute("add_error","用户名重复");
            req.getRequestDispatcher("/userlist/add.jsp").forward(req,resp);
        }
    }
}
